#include "demohelper.hpp"

int test_epoll(DemoHelper *dh, int timeout)
{
    EpollHelper *eph = new EpollHelper();
    int ret;

    for (const auto &f: dh->get_files()) {
        f->set_nonblock(true);
        eph->add_epoll(f, POLLIN);
    }

    std::cout << "timeout: " << timeout << std::endl;
    do {
        std::vector<struct epoll_event> events;
        ret = eph->wait(events, timeout);
        if (ret < 0) {
            std::cerr << "epoll wait error: " << errno << std::endl;
            return ret;
        } else if (ret == 0) {
            std::cerr << "epoll wait timeout" << std::endl;
            return -ETIMEDOUT;
        }

        for (const auto &it: events) {
            int fd = it.data.fd;
            FileDesc *f = eph->get_file_from_fd(fd);
            if (!f) {
                std::cerr << "unkown fd: " << fd << std::endl;
                continue;
            }

            std::cout << "read from: " << f->get_name() << std::endl;
            std::string readbuf = f->read();
            std::cout << readbuf << std::endl;
            if (readbuf == "quit") {
                return 0;
            }
        }
    } while (1);

    delete eph;

    return 0;
}

int main(int argc, const char *argv[])
{
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " timeout(ms)" << std::endl;
        return -1;
    }

    DemoHelper *dh = new DemoHelper(5);
    int timeout = std::stoi(argv[1]);
    int ret;

    dh->create_files();

    ret = test_epoll(dh, timeout);

    dh->remove_files();

    delete dh;

    return ret;
}
